<?php

namespace Admin\Controller;

use Admin\Controller\AdminController;

/**
 * @author wangnaixin
 * @todo 首页模块
 * @menu 首页
 * @menuAuto index
 * @order 1
 * @icon index.png
 */
class IndexController extends AdminController {
    
    public function __construct() {
        $_SESSION['sys_left_logo'] = 'logo.png';
        parent::__construct();
        
    }
    
    /**
     * @author wangnaixin
     * @todo 后台管理首页
     */
    public function index(){
        $this->display();
    }

    public function getGeneralStatistics() {
        $data = array(
            'sellerOrders' => $this->getMaxSellerOrders(),
            'buyerOrders' => $this->getMaxBuyerOrders(),
            'maxTrips' => $this->getMaxTrips(),
            'totalAmount' => $this->getTotalAmount()
        );

        $this->ajaxReturn($data);
    }

    private function getMaxSellerOrders() {
        $sql = 'select b.*,u.user_name,u.real_name,u.avatar from users u,';
        $sql .= '(select seller_id,total from (select seller_id,count(1) as total from `order` where type=1 group by seller_id) o order by o.total desc limit 1) b ';
        $sql .= 'where u.id=b.seller_id';
        $result = M()->query($sql);
        $data = reset($result);
        return $data;
    }

    private function getMaxBuyerOrders() {
        $sql = 'select b.*,u.user_name,u.real_name,u.avatar from users u,';
        $sql .= '(select buyer_id,total from (select buyer_id,count(1) as total from `order` where type=1 group by buyer_id) o order by o.total desc limit 1) b ';
        $sql .= 'where u.id=b.buyer_id';
        $result = M()->query($sql);
        $data = reset($result);
        return $data;
    }

    private function getMaxTrips() {
        $sql = 'select b.*,u.user_name,u.real_name,u.avatar from users u,';
        $sql .= '(select user_id,total from (select user_id,count(1) as total from `trip` group by user_id) o order by o.total desc limit 1) b ';
        $sql .= 'where u.id=b.user_id';
        $result = M()->query($sql);
        $data = reset($result);
        return $data;
    }

    private function getTotalAmount() {
        $sql = 'select ifnull(sum(ifnull(reward,0)+ifnull(deposit,0)+ifnull(brokerage,0)),0) as total from `order`';
        $result = M()->query($sql);
        $data = reset($result);
        return number_format($data['total'],2);
    }
    
}